<template>
  <!-- 自定义模板表格显示组件 -->
  <div class="mdt-table-body">
    <slot name="condition"></slot>
    <div class="table-box">
      <table>
        <thead>
          <tr v-for="(r, index) in headerData" :key="'head' + index">
            <template v-for="item in r">
              <th
                :style="item.top"
                :ref="item.id"
                :class="{ 'dw-item': item.prop === 'DWMC' }"
                v-if="!item.isMerge"
                :key="item.id"
                :rowspan="item.rowspan"
                :colspan="item.colspan"
              >
                <div class="text-s">
                  <span class="label-s">{{ item.label }}</span>
                  <div
                    v-if="filterFlag && item.bdsdy && item.bdsdy !== 'DWMC'"
                    class="filter-box"
                  >
                    <el-popover placement="top" trigger="click">
                      <div class="pop-box">
                        <el-select
                          v-model="rulesData[item.bdsdy]"
                          style="width: 80px; float: left; height: 34px"
                          placeholder="符号"
                          size="small"
                          clearable
                        >
                          <el-option
                            v-for="item in markList"
                            :key="item"
                            :label="item"
                            :value="item"
                          >
                          </el-option>
                        </el-select>
                        <el-input
                          style="width: 100px; margin-left: 16px; float: left"
                          v-model="filterData[item.bdsdy]"
                          placeholder="数值"
                          size="small"
                        ></el-input>
                        <div style="float: right; margin-left: 8px">
                          <button
                            @click="filterMethod(item.bdsdy)"
                            class="mlt_btn_operation"
                          >
                            筛选
                          </button>
                        </div>
                      </div>
                      <i
                        slot="reference"
                        class="opera-icon el-icon-arrow-down"
                      ></i>
                    </el-popover>
                  </div>
                  <div
                    v-if="sortFlag && item.bdsdy && item.bdsdy !== 'DWMC'"
                    class="sort-box"
                  >
                    <span
                      class="caret-wrapper"
                      :class="{
                        [sortItemInfo.sortValue]: sortItemInfo.id == item.id
                      }"
                      @click.stop="changeSort(item)"
                    >
                      <i
                        @click.stop="setSort(item, 'asc')"
                        class="sort-caret ascending"
                      ></i>
                      <i
                        @click.stop="setSort(item, 'desc')"
                        class="sort-caret descending"
                      ></i>
                    </span>
                  </div>
                </div>
              </th>
            </template>
          </tr>
        </thead>
        <tr v-for="(r, index) in showTableData" :key="'body' + index">
          <td
            :class="{
              'c-pointer': intoFlag && item === 'DWMC' && !r.DWBM.includes('B')
            }"
            @click="searchCurDwData(r, item)"
            v-for="(item, idx) in headerList"
            :key="index + '-' + idx"
          >
            <div class="cell">
              {{ r[item] }}
            </div>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import { getTree, getLeafNodes } from "./getTableInfo";
export default {
  name: "multilevel-table",
  props: {
    // 过滤
    filterFlag: {
      type: Boolean,
      default: () => false
    },
    // 排序
    sortFlag: {
      type: [Boolean, Array],
      default: () => false
    },
    // 固定表头
    fixedHeader: {
      type: Boolean,
      default: () => true
    },
    // 控制下钻
    intoFlag: {
      type: Boolean,
      default: () => true
    },
    // 表头数据
    headerData: {
      type: Array,
      default: () => []
    },
    // 表格显示数据
    tableData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 符号信息
      markList: [">", ">=", "=", "<=", "<"],
      // 表头列信息
      headerList: [],
      // 显示的表格数据
      showTableData: [],
      // 当前过滤数据
      filterData: {},
      // 排序字段
      sortItemInfo: {},
      // 筛选规则
      rulesData: {}
    };
  },
  watch: {
    headerData(nVal) {
      if (nVal.length > 0) {
        this.initPageData();
      }
    }
  },
  mounted() {
    this.initPageData();
  },
  methods: {
    // 改变排序类型
    changeSort(item) {
      if (item.id == this.sortItemInfo.id) {
        let value = this.sortItemInfo.sortValue;
        switch (value) {
          case "asc":
            value = "desc";
            break;
          case "desc":
            value = "";
            break;
          default:
            value = "asc";
            break;
        }
        this.$set(this.sortItemInfo, "sortValue", value);
      } else {
        this.sortItemInfo = { ...item };
        this.$set(this.sortItemInfo, "sortValue", "asc");
      }
      this.getSortResult();
    },
    // 获取筛选后数据
    getFilterData() {
      let tableData = this._.cloneDeep(this.tableData);
      for (let key in this.filterData) {
        if (!this.filterData[key] || !this.rulesData[key]) {
          continue;
        }
        let rulesValue = this.rulesData[key];
        if (rulesValue == "=") {
          rulesValue = "==";
        }
        tableData = tableData.filter(el => {
          if (!/\d/.test(String(el[key]))) {
            return false;
          }
          return eval(
            `${this.getNumber(el[key])} ${rulesValue} ${this.getNumber(
              this.filterData[key]
            )}`
          );
        });
      }
      return tableData;
    },
    // 获取数字
    getNumber(value) {
      if (/\d/.test(value + "")) {
        let arr = String(value).match(/-?[0-9]+.*[0-9]*/g);
        return (arr[0] *= 1);
      } else if (value == "" || value === undefined || value == "-") {
        return -Infinity;
      } else {
        return 0;
      }
    },
    // 根据排序信息设置数据
    getSortResult() {
      let tableData = this._.cloneDeep(this.showTableData);
      if (this.sortItemInfo.sortValue) {
        this.showTableData = this._.orderBy(
          tableData,
          [this.sortItemInfo.bdsdy],
          [this.sortItemInfo.sortValue]
        );
      } else {
        this.showTableData = this.getFilterData();
      }
    },
    // 重置
    resetMethod() {
      Object.keys(this.filterData).forEach(params => {
        this.filterData[params] = "";
      });
      Object.keys(this.rulesData).forEach(params => {
        this.rulesData[params] = "";
      });
      this.sortItemInfo = {};
      this.showTableData = this._.cloneDeep(this.tableData);
    },
    // 设置排序类型
    setSort(item, sortParams) {
      if (item.id == this.sortItemInfo.id) {
        let value = this.sortItemInfo.sortValue == sortParams ? "" : sortParams;
        this.$set(this.sortItemInfo, "sortValue", value);
      } else {
        this.sortItemInfo = { ...item };
        this.$set(this.sortItemInfo, "sortValue", sortParams);
      }
      this.getSortResult();
    },
    // 筛选
    filterMethod(params) {
      const filterValue = this.filterData[params];
      if (this.rulesData[params] == "" && filterValue !== "") {
        this.$message.info("请输入筛选规则!");
        return;
      }
      if (filterValue == "" && this.rulesData[params] !== "") {
        this.$message.info("请输入筛选数据!");
        return;
      }
      this.showTableData = this.getFilterData();
      this.getSortResult();
    },
    initPageData() {
      if (!Array.isArray(this.headerData) || this.headerData.length === 0) {
        return;
      }
      this.getHeaderList();
      this.resetMethod();
    },
    // 获取表头指标数据信息
    getHeaderList() {
      const treeData = getTree({
        headerData: this.headerData,
        includeDw: true
      });
      let leafNodes = [];
      getLeafNodes(treeData, leafNodes);
      this.headerList = leafNodes.map(el => {
        let prop = el.prop;
        if (el.hsgs) {
          prop = el.hsgs.replace("$1", el.prop);
        }
        return prop;
      });
      for (let oneEl of this.headerData) {
        for (let twoEl of oneEl) {
          if (!twoEl.isMerge) {
            let prop = twoEl.prop;
            if (twoEl.hsgs) {
              prop = twoEl.hsgs.replace("$1", twoEl.prop);
            }
            if (this.headerList.includes(prop)) {
              this.$set(twoEl, "bdsdy", prop);
            }
          }
        }
      }
      this.$nextTick(() => {
        if (this.fixedHeader) {
          this.setTop();
        }
      });
    },
    // 设置
    setTop() {
      for (let oneEl of this.headerData) {
        for (let twoEl of oneEl) {
          this.$nextTick(() => {
            !twoEl.isMerge && this.$set(twoEl, "top", this.getTop(twoEl.id));
          });
        }
      }
    },
    // 获取表头元素top
    getTop(id) {
      if (this.$refs[id]) {
        return {
          top: this.$refs[id][0].offsetTop + "px"
        };
      }
    },
    // 查询点击单位的数据
    searchCurDwData(r, params) {
      if (!this.intoFlag || params !== "DWMC" || r.DWBM.includes("B")) {
        return;
      }
      this.$emit("search-dwdata", { dwbm: r.DWBM });
    }
  }
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>